package com.flamingo.xiaomiweather.logic.network;

import com.flamingo.xiaomiweather.logic.model.PlaceResponse;

import java.util.concurrent.CompletableFuture;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class XiaomiWeatherNetwork {

    private final PlaceService placeService = new ServiceCreator().create(PlaceService.class);

    public CompletableFuture<PlaceResponse> searchPlaces(String query) {
        return await(placeService.searchPlaces(query));
    }

    private <T> CompletableFuture<T> await(Call<T> call) {
        CompletableFuture<T> future = new CompletableFuture<>();
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.body() != null) {
                    future.complete(response.body());
                } else {
                    future.completeExceptionally(new RuntimeException("response body is null"));
                }
            }
            @Override
            public void onFailure(Call<T> call, Throwable t) {
                future.completeExceptionally(t);
            }
        });
        return future;
    }
}
